<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\admin\controller\match;

use app\admin\model\User;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\library\InviteCode;
use app\common\manager\LogManager;
use app\common\model\Member;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Ranks extends Backend
{

    /**
     * Member模型对象
     * @var \app\admin\model\match\Member
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\match\Member;
        $this->view->assign("isOutList", $this->model->getIsOutList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $matchId = $this->request->param("ids");
        $mid = $this->request->param("mid");
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['match','user'])
                    ->where($where)
                    ->where(function ($query) use ($mid) {
                        if ($mid){
                            return $query->where('match_id',$mid);
                        }
                    })
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {

                if ($row->out_round){
                    $row->out_round_title = \app\admin\model\match\Round::where('round_id',$row->out_round)->value('title') ?? '';
                }else{
                    $row->out_round_title = '';
                }
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assign('matchId', $matchId);
        return $this->view->fetch();
    }

    public function ranks(){
        $matchId = $this->request->param("matchId");
        $matchInfo = \app\admin\model\Match::where('m_id',$matchId)->find();
        if (!$matchInfo) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($matchInfo[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $result = false;
        Db::startTrans();
        try {
            $memberInfo = Member::where('match_id', $matchId)->field('id,score')->select();
            $data = [];
            if ($memberInfo){
                foreach ($memberInfo as $k=>$v){
                    $data[$v['id']] = $v['score'];
                }
            }

            if($data){
                $ranked = ranks($data);
                if ($ranked){
                    try {
                        foreach ($ranked as $key=>$val) {
                            Member::where('id',$key)->update(['ranks'=>$val,'update_time'=>time()]);
                        }
                    }catch (Exception $e){
                        Db::rollback();
                    }

                }
            }
            $result = true;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success('success');
    }


}
